import { forwardRef, useEffect, useState } from 'react'
import CommonModal from '@/views/ShoppingCart/components/CommonEditModal.tsx'
import { localShoppingData, tempData } from '@/views/ShoppingCart/LocalShoppingData.ts'
import { allAreaList, allCityList, allProvinceList } from '@hs-admin/utils'
import CommonTree from '@/views/ShoppingCart/components/CommonTree.tsx'
import { Checkbox } from 'antd'

const levelOneData = allProvinceList.map((item) => ({
  title: item.label,
  key: item.value
}))
const levelTwoData = allProvinceList.map((item) => ({
  title: item.label,
  key: item.value,
  children: (allCityList[item.value as string] ?? []).map((it) => ({
    title: it.label,
    key: it.value
  }))
}))
const levelThreeData = allProvinceList.map((item) => ({
  title: item.label,
  key: item.value,
  children: (allCityList[item.value as string] ?? []).map((it) => ({
    title: it.label,
    key: it.value,
    children: (allAreaList[it.value as string] ?? []).map((child) => ({
      title: child.label,
      key: child.value
    }))
  }))
}))

const AreaMap = {
  省: levelOneData,
  市: levelTwoData,
  区: levelThreeData
}

const EditAreaScope = forwardRef(
  (props: { itemId: string; areaLevel: '省' | '市' | '区'; done: (() => void) | undefined; disabled?: boolean }, ref) => {
    const notEditable = !!props.disabled

    const haveCommon = !!localShoppingData('common')

    const treeAreaData = AreaMap[props.areaLevel]
    const [areaList, setAreaList] = useState([])

    const [useParent, setUseParent] = useState(false)

    useEffect(() => {
      let data = localShoppingData(props.itemId, 'areaList') ?? []
      if (props.itemId !== 'common') {
        data = tempData('areaList') ?? []
        const useP2 = tempData('p2') ?? false
        setUseParent(useP2)
      } else {
        setUseParent(false)
      }
      setAreaList(data)
    }, [props.itemId])

    return (
      <CommonModal
        ref={ref}
        onOk={() => {
          if (notEditable) return
          props.done?.()
          if (props.itemId === 'common') {
            localShoppingData(props.itemId, { areaList })
          } else {
            tempData({ areaList })
            tempData({
              p2: useParent
            })
          }
        }}
        onCancel={() => {
          console.log('取消')
        }}
        title="区域范围选择">
        <div className="max-h-70vh">
          {props.itemId !== 'common' && haveCommon && (
            <div>
              <Checkbox
                checked={useParent}
                onChange={(e) => {
                  setUseParent(e.target.checked)
                  if (e.target.checked) {
                    setAreaList([])
                  }
                }}>
                使用整体范围
              </Checkbox>
            </div>
          )}
          {!useParent && (
            <CommonTree
              disabled={notEditable}
              defaultExpandedKeys={[]}
              checkedKeys={areaList}
              treeData={treeAreaData}
              onCheck={(value) => {
                if (value.length) {
                  let finalArr = []
                  const maps = Object.groupBy(value, (it) => it.slice(0, 2))
                  Object.keys(maps).forEach((key) => {
                    if (maps[key].includes(`${key}0000`)) {
                      finalArr.push(`${key}0000`)
                    } else {
                      const secondMaps = Object.groupBy(maps[key], (it) => it.slice(0, 4))
                      Object.keys(secondMaps).forEach((second) => {
                        if (secondMaps[second].includes(`${second}00`)) {
                          finalArr.push(`${second}00`)
                        } else {
                          finalArr = finalArr.concat(secondMaps[second])
                        }
                      })
                    }
                  })
                  setAreaList(finalArr)
                } else {
                  setAreaList(value)
                }
              }}
            />
          )}
        </div>
      </CommonModal>
    )
  }
)

export default EditAreaScope
